﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace System
{
    /// <summary>
    /// 针对对象<see cref="Object"/>进行扩展
    /// </summary>
    /// <creator>marc</creator>
   public static class ObjectExtensions
    {
        /// <summary>
        /// 获取指定类型<typeparamref name="TAttribute"/>的属性对象
        /// </summary>
        /// <typeparam name="TAttribute">属性类型</typeparam>
        /// <param name="object">对象</param>
        /// <returns></returns>
        public static TAttribute GetAttribute<TAttribute>(this object @object)
        {
            Array values = Enum.GetValues(@object.GetType());
            foreach (var value in values)
            {
                if (!value.Equals(@object))
                {
                    continue;
                }

                var name = value.ToString();
                FieldInfo field = value.GetType().GetField(name);
                object[] attributes = field.GetCustomAttributes(typeof(TAttribute), false);
                if (attributes != null && attributes.Length > 0 && attributes[0] is TAttribute destAttribute)
                {
                    return destAttribute;
                }
            }

            return default;
        }
    }
}
